package com.mxw.component.security.interceptor;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.json.JSONConfig;
import cn.hutool.json.JSONUtil;
import com.mxw.commons.errorcode.GlobalErrorCode;
import com.mxw.commons.restful.Result;
import com.mxw.component.security.properties.CloudSecurityProperties;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Base64Utils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/** @Description TODO @Author RingKo @Date 2021/12/7 22:22 @Version 1.0 */
@Slf4j
public class ServerProtectInterceptor implements HandlerInterceptor {

  private CloudSecurityProperties properties;

  @Override
  public boolean preHandle(
      @NonNull HttpServletRequest request,
      @NonNull HttpServletResponse response,
      @NonNull Object handler) {

    if (Boolean.FALSE.equals(properties.getOnlyFetchByGateway())) {
      return true;
    }

    String token = request.getHeader(properties.getGatewayTokenHeader());
    String gatewayToken =
        new String(Base64Utils.encode(properties.getGatewayTokenValue().getBytes()));
    if (CharSequenceUtil.equals(gatewayToken, token)) {
      return true;
    } else {
      log.error(GlobalErrorCode.ILLEGAL_REQUEST.getLogString(null));
      Result result = Result.respondWithIErrorCode(GlobalErrorCode.ILLEGAL_REQUEST);
      response.setHeader("Content-Type", "application/json;charset=UTF-8");
      response.setContentType("application/json;charset=UTF-8");
      response.setStatus(HttpServletResponse.SC_OK);
      PrintWriter out = null;
      try {
        out = response.getWriter();
        out.print(JSONUtil.toJsonStr(result, JSONConfig.create().setIgnoreNullValue(false)));
        out.flush();
      } catch (Exception e) {
        log.error(e.getMessage(), e);
      } finally {
        if (out != null) {
          out.close();
        }
      }
      return false;
    }
  }

  public void setProperties(CloudSecurityProperties properties) {
    this.properties = properties;
  }
}
